package controllers

import auth._
import auth.AuthTool._
import dao._
import models.Tables._
import org.joda.time.DateTime
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.Tool
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import implicits.Implicits._
import org.mindrot.jbcrypt.BCrypt
import shared.pojo.Pojo._

import scala.concurrent.Future
import upickle.default._

/**
 * Created by Administrator on 2019/8/7
 */
class MemberController @Inject()(cc: ControllerComponents,
                                )(
                                  implicit val memberDao: MemberDao,
                                  implicit val accountDao: AccountDao,
                                  implicit val companyMemberDao: CompanyMemberDao,
                                  implicit val specialMemberDao: SpecialMemberDao,
                                  implicit val authAction: AuthActionWrapper,
                                ) extends
  AbstractController(cc) {

  import shared.pojo.Member._

  def add = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[Add.Request])
    val row = MemberRow(0, data.account, data.password.hashedPassword, new DateTime())
    memberDao.insert(row).map { x =>
      val response = ValidData(valid = true)
      Ok(writeJs(response))
    }
  }

  def all = adminAuth.async { implicit request =>
    memberDao.selectAll.map { x =>
      val array = x.map(x => writeJs(x))
      Ok(writeJs(array))
    }
  }

  def delete = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[IdData])
    memberDao.deleteById(data.id).map { x =>
      val response = ValidData(valid = true)
      Ok(writeJs(response))
    }
  }

  def getById = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[IdData])
    memberDao.selectById(data.id).map { x =>
      Ok(writeJs(x))
    }
  }

  def update = adminAuth.async { implicit request =>
    val data = Tool.transformRq.transform(reader[Update.Request])
    memberDao.selectByAccountSome(data.account).flatMap { dbUser =>
      val row = dbUser.copy(password = data.password.hashedPassword)
      memberDao.update(row).map { x =>
        val response = ValidData(valid = true)
        Ok(writeJs(response))
      }
    }
  }


}
